function sameasmain(){
	if($("#sameasmainoffice").is(":checked")){
		$("#addressbill").val($("#addressmain").val());
		$("#country2 option[value='"+$("#countrymain").val()+"']").attr('selected','selected');
		var t2 = $("[id*=country2]:visible")[0].selectedIndex;
		print_stateCorporate("state2",t2);
		$("#state2 option[value='"+$("#statemain").val()+"']").attr('selected','selected');
		$("#citybill").val($("#citymain").val());
		$("#zipcodebill").val($("#zipcodemain").val());
	}else{
		$("#addressbill").val("");
		$("#country2 option:first").attr('selected','selected');
		var t2 = $("[id*=country2]:visible")[0].selectedIndex;
		print_stateCorporate("state2",t2);
		$("#citybill").val("");
		$("#zipcodebill").val("");
	}
}

function samecontactperson(){
	if($("#samecontactperson").is(":checked")){
		$("#salutationbillcontact option[value='"+$("#salutationperson").val()+"']").attr('selected','selected');//
		$("#firstnamecontactperson").val($("#firstnameperson").val());
		$("#lastnamecontactperson").val($("#lastnameperson").val());
		$("#designationcontactperson").val($("#designationperson").val());
		$("#officephonecontactperson").val($("#phoneperson").val());
		$("#extncontactperson").val($("#extnperson").val());
		$("#officefaxcontactperson").val($("#officefaxperson").val());
		$("#emailcontactperson").val($("#emailperson").val());
		$("#mobilecontactperson").val($("#mobileperson").val());
		$("#gendercontactperson option[value='"+$("#genderperson").val()+"']").attr('selected','selected');
		$("#datecontactperson option[value='"+$("#dateperson").val()+"']").attr('selected','selected');
		$("#monthcontactperson option[value='"+$("#monthperson").val()+"']").attr('selected','selected');
		$("#yearcontactperson option[value='"+$("#yearperson").val()+"']").attr('selected','selected');
		$("#websitecontactperson").val($("#websiteperson").val());
	}else{
		$("#salutationbillcontact option:first").attr('selected','selected');//
		$("#firstnamecontactperson").val("");
		$("#lastnamecontactperson").val("");
		$("#designationcontactperson").val("");
		$("#officephonecontactperson").val("");
		$("#extncontactperson").val("");
		$("#officefaxcontactperson").val("");
		$("#emailcontactperson").val("");
		$("#mobilecontactperson").val("");
		$("#gendercontactperson option:first").attr('selected','selected');
		$("#datecontactperson option:first").attr('selected','selected');
		$("#monthcontactperson option:first").attr('selected','selected');
		$("#yearcontactperson option:first").attr('selected','selected');
		$("#websitecontactperson").val("");
	}
}

function setCountry(){
	print_countryCorporate("country3");
	var t3 = $("[id*=country3]:visible")[0].selectedIndex;
	print_stateCorporate("state3",t3);
}

function ClearSpanSelection()
{
	this.span = 1;
	if($(".SlectedSpan").size() == 0)
		return;
	var startDom = $(".SlectedSpan").parent();
	var span = parseInt(startDom.attr("colspan"));
	startDom.html(htmlStartDom);
	startDom.removeAttr("colspan");
	for(var i = span;i>1;i--)
	{
		var dom = tmpDom.pop();
		startDom.after(dom);
		if(dom!=null){
			dom.drag(DragObject);
			dom.drag("end",DropObject);
		}
	}
}

function setDatepicker(dateStart,dateEnd,vcId){
	$("[name='srTxtFrom']:visible").datepicker({
        changeMonth: true,
        changeYear: true,
        monthNamesShort: ShortMonth,
		monthNames: ShortMonth,
		dayNamesShort: ShortDay,
		dayNames: ShortDay,
        showOn: 'button',
        buttonImage: '/images/components/editres/carendar.png',
        buttonImageOnly: true,
        onSelect: function( selectedDate ) {
        	var date = new Date(selectedDate);
        	$("[name='srTxtFrom']:visible").attr("valfrom",date.toSystemFormat());
        	$("[name='srTxtFrom']:visible").val(date.getFormatedString());
            $( "[name='srTxtTo']:visible" ).datepicker( "option", "minDate", selectedDate );
          }
    });
	$("[name='srTxtTo']:visible").datepicker({
        changeMonth: true,
        changeYear: true,
        monthNamesShort: ShortMonth,
		monthNames: ShortMonth,
		dayNamesShort: ShortDay,
		dayNames: ShortDay,
        showOn: 'button',
        buttonImage: '/images/components/editres/carendar.png',
        buttonImageOnly: true,
        onSelect: function(selectedDate) {
        	var date = new Date(selectedDate);
        	$("[name='srTxtTo']:visible").attr("valfrom",date.toSystemFormat());
        	$("[name='srTxtTo']:visible").val(date.getFormatedString());
        }
    });
	if(vcId!=null){
		$("[name='srTxtFrom']:visible").attr("vcid",vcId);
		$("[name='srTxtFrom']:visible").attr("startdate",dateStart);
		$("[name='srTxtTo']:visible").attr("enddate",dateEnd);
		$("[name='srTxtFrom']:visible").attr("valfrom",dateStart);
		$("[name='srTxtTo']:visible").attr("valfrom",dateEnd);
		$("[name='srTxtFrom']:visible").val(new Date(dateStart).getFormatedString());
		$("[name='srTxtTo']:visible").val(new Date(dateEnd).getFormatedString());
	}else{
		if($("[edit=true]").size()!=0){
			var dateStart = $("[edit=true]").find("td:first").attr("startdate");
			var dateEnd = $("[edit=true]").find("td:first").attr("enddate");
			
			$("[name='srTxtFrom']:visible").attr("vcid","");
			$("[name='srTxtFrom']:visible").attr("startdate","");
			$("[name='srTxtTo']:visible").attr("enddate","");
			$("[name='srTxtFrom']:visible").attr("valfrom",dateStart);
			$("[name='srTxtTo']:visible").attr("valfrom",dateEnd);
			$("[name='srTxtFrom']:visible").val(new Date(dateStart).getFormatedString());
			$("[name='srTxtTo']:visible").val(new Date(dateEnd).getFormatedString());
		}else{
			$("[name='srTxtFrom']:visible").attr("vcid","");
			$("[name='srTxtFrom']:visible").attr("startdate","");
			$("[name='srTxtTo']:visible").attr("enddate","");
			$("[name='srTxtFrom']:visible").attr("valfrom","");
			$("[name='srTxtTo']:visible").attr("valfrom","");
			$("[name='srTxtFrom']:visible").val("");
			$("[name='srTxtTo']:visible").val("");
		}
	}
}

function gotoaddAgent(dom){
	waitingDialog({});
	$("[id=tableaddagent]").attr("style","display:;");
	$("[id=tableaddagent]").load("/adminconsole/Console/Agent/AddAgent.jsp",function(responseText, textStatus, XMLHttpRequest) {
		setBarAgent();
		//$("[name=numberonly]").ForceNumericOnly();
		$("[id=tableagent]").attr("style","display:none");
	});
}
//set bar
function setBarAgent(id,type){
	setTitleBar(id,type);
	//company
	print_countryCorporate("country");
	print_countryCorporate("country2");
	var t1 = $("[id*=country]:visible")[0].selectedIndex;
	print_stateCorporate("statemain",t1);
	var t2 = $("[id*=country2]:visible")[0].selectedIndex;
	print_stateCorporate("state2",t2);
	//salutation
	var services = [];
	services.push(["/popupService",{doClass:"loadSalutation"},"Salutation",null]);
	loadSharedDataIfNotExist(services,function(){
		var opts = SharedData.Salutation.length;
		if($("[id*=salutation] > option").length == 0)
			for ( var i = 0; i < opts; i++)
				$("[id*=salutation]").append( $("<option>").val(SharedData.Salutation[i].id).html(SharedData.Salutation[i].title));
	});
	yearselectDropdown($("[id*=year]"));
	monthselectDropdown($("[id*=month]"));
	generaldayoption($("[id*=date]"));
	closeWaitingDialog();
}
function setTitleBar(id,subTitle){
	var title =	$(".breadcrumb").html().trim();
	if(id!=null){
		if(id=="detail"){
			$(".breadcrumb").replaceWith("<div class='breadcrumb' >" +
					"<a href='javascript:showAgent();'><span class='link' id='titleLinkagent'>"+title+"</span></a>/"+
					'<span id="titleName" >'+subTitle+"</span></div>");
		}else if(subTitle=="detailedit"){
			var title = $($(title)[0]).find("span").html();
			$(".breadcrumb").replaceWith("<div class='breadcrumb' >" +
					"<a href='javascript:showAgent();'><span class='link' id='titleLinkagent'>"+title+"</span></a>/"+
					'<span id="titleName" >'+console_editagent+"</span></div>");
		}else{
			$(".breadcrumb").replaceWith("<div class='breadcrumb' >" +
					"<a href='javascript:showAgent();'><span class='link' id='titleLinkagent'>"+title+"</span></a>/"+
					'<span id="titleName" >'+console_editagent+"</span></div>");
		}
	}else{
		$(".breadcrumb").replaceWith("<div class='breadcrumb' >" +
		"<a href='javascript:showAgent();'><span class='link' id='titleLinkagent'>"+title+"</span></a>/"+
		'<span id="titleName" >'+console_addagent+"</span></div>");
	}
	
}

function showAgent(id,type,userDisplay){
	waitingDialog({});
	var displayAdd = $("[id=tableaddagent]").css('display');
	if(displayAdd!="none"){
		var title =	$("#titleLinkagent").html().trim();
		$(".breadcrumb").replaceWith("<div class='breadcrumb'>"+title+"</div>");
		$("[id=tableaddagent]").attr("style","display:none");
		$("[id=tableagent]").attr("style","display:");
	}else if(userDisplay!=null){
		var title =	$("#titleLinkPOSCategory").html().trim();
		$(".breadcrumb").replaceWith("<div class='breadcrumb'>"+title+"</div>");
		$("[id=tableaddagent]").attr("style","display:none");
		$("[id=tableagent]").attr("style","display:");
		$(".destitle").replaceWith('<div class="destitle">'+console_suggestAgent+'</div>');
		$(".titlelist").replaceWith('<div class="titlelist">'+console_listAgent+'<span id="listsize">'+$("#listsize").html()+'</span>'+'</div>');
		$("[name=add_agent]").val(console_btnAddAgent);
		$("[name=add_agent]").attr('onclick','gotoaddAgent($(this))');
		$("[name=del_agent]").val(console_btnDeleteAgent);
		$("[name=del_agent]").attr('onclick','deleteAgent()');
	}
	
	if(id == null||type=="add"||type=="del"){
		if($("[name=maxEntries]").val() == null){
			var line = 10;
		}else{
			var line = $("[name=maxEntries]").val();
		}
		if($("[name=selectpage]").val() == null){
			var pagePointer = 1; 
		}else{
			var pagePointer = $("[name=selectpage]").val(); 
		}
	}else if(id == "next"){
		var line = $("[name=maxEntries]").val();
		var pagePointer = parseInt($("[name=selectpage]").val())+1;
	}else if(id == "previous"){
		var line = $("[name=maxEntries]").val();
		var pagePointer = parseInt($("[name=selectpage]").val())-1;		
	}
	var link = "/agencyService";
	var data = { func: "getAgency",
				offset: (line*pagePointer)-line,
				line: line,
				pagePointer: pagePointer
					}
	simpleservice(link,data,showAgentList);
}
function showAgentList(data){
	$("[id=showList]").load("/adminconsole/Console/Agent/mainAgent.jsp",function(responseText, textStatus, XMLHttpRequest) {
		objArrayFirst = JSON.parse(data);
		var checkLogOut = checkSessionAdmin(objArrayFirst);
		if(checkLogOut)
			return;
		var sumtext = "";
		var text = "";
		var pageAmount = Math.ceil(objArrayFirst.dataAmount/objArrayFirst.lineAmount);
		var line = objArrayFirst.lineAmount;
		var pagePointer = objArrayFirst.pageNumber;
		var objArray = objArrayFirst.data;
		$("#listsize").html("("+objArrayFirst.dataAmount+")");
		var lineNumber = (line * pagePointer) - (line-1);
		var Percent = "";
		var description = "";
		for(var i = 0;i< objArray.length+1;i++){
				if(objArray[i]!=undefined){
					var agency = "-";
					var country = "-";
					var phone = "-";
					var email = "-";
					if(objArray[i].agency!=null)
						agency = objArray[i].agency;
					if(objArray[i].maincountry!=null)
						country = objArray[i].maincountry;
					if(objArray[i].mobileperson!=null)
						phone = objArray[i].mobileperson;
					if(objArray[i].emailperson!=null)
						email = objArray[i].emailperson;
				}
				if(i != objArray.length ){
					text = "<tr id=\"row_"+objArray[i]['id']+"\" style=\"border: 0px;\"> " +
							"<td id=\"col_1\" align=\"center\"> "+(lineNumber+i)+". </td>"+
							"<td><input type=\"checkbox\" id=\"id_"+i+"\" name=\"ids[]\" value=\""+objArray[i]['id']+"\"> </td>"+
							"<td align=\"left\"> "+objArray[i]['displayId']+" </td>"+
							"<td align=\"left\" class='link' displaydetail='"+objArray[i]['id']+"'  onclick=\"DetailAgent($(this),"+objArray[i]['id']+")\" >"+agency+" </td>"+
							"<td>"+country+"</td>"+
							"<td>"+phone+"</td>"+
							"<td>"+email+"</td>"+
							"<td align=\"center\"><a href=\"#\" onclick=\"gotoeditAgent("+objArray[i]['id']+")\">Edit</a></td>"+
							"<td align=\"center\"><a href=\"#\" onclick=\"changeStatusAgnet("+objArray[i]['id']+") \"> " +
							"<span id =status"+objArray[i]['id']+">"+objArray[i]['status']+"</a>" +
							"</td>" +
							"<td></td>"+
							"<td class='link' onclick='showUserAgent(undefined,undefined,$(this))'>"+console_user+"</td>"+
							"</tr>";
					sumtext += text;
				}else{
					text = "<tr>"+
					"<td colspan=\"13\" style=\"padding:0;\">"+
					"<table class=\"tablefoot\" width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">" +
					"<tbody>"+
						"<tr>"+
							"<td width=\"33%\" align=\"left\">"+foor_page+"&nbsp;"+
								"<select name=\"selectpage\" onchange=\"showAgent()\">"+
								"</select>&nbsp;"+foor_of+"&nbsp;<span id=\"pageAmount\">1</span>"+
							"</td>"+
							"<td width=\"31%\" align=\"center\">"+foor_view+
								"<select name=\"maxEntries\" onchange=\"showAgent()\">"+
									"<option style=\"color:#000000\"  value=\"10\">10</option>"+
									"<option style=\"color:#000000\"  value=\"20\">20</option>"+
									"<option style=\"color:#000000\"  value=\"50\">50</option>"+
									"<option style=\"color:#000000\"  value=\"100\">100</option>"+
									"<option style=\"color:#000000\"  value=\"100000\">All</option>"+
								"</select>"+foor_rpp+" </td>" +
								"<td width=\"36%\" align=\"right\"><span id=\"previous\">&lt;&lt;"+foor_pre+"</span> |" +
								" <span id=\"next\">"+foor_next+"&gt;&gt;</span></td></tr>"+
								"</tbody></table></td></tr>";
					sumtext += text;
				}
		}
		$("#showList tr").not($("#showList tr").first()).remove();
		$("#showList").append(sumtext);
		$("#pageAmount").text(pageAmount);
		if(pagePointer+1 <= pageAmount){
			$("#next").attr("onclick","showAgent(id)");
			$("#next").html("<a href=\"#\">Next&gt;&gt;</a>");
		}
		if(pagePointer > 1){
			$("#previous").attr("onclick","showAgent(id)");
			$("#previous").html("<a href=\"#\">&lt;&lt;Previous</a>");
		}
		$("[name=maxEntries]").val(line);
		for ( var i = 0; i < pageAmount; i++) {
			$("[name=selectpage]").append(
					$("<option>").val((i+1)).html((i+1)));
			}
		$("[name=selectpage]").val(pagePointer);
		closeWaitingDialog();
	});
}

function AddEventClickAgent(id){
	var title = $("#title").val();
	//main
	var address_main = $("#addressmain").val();
	var country_main = $("#countrymain").val();
	var state_main = $("#statemain").val();
	var city_main =$("#citymain").val();
	var zipcode_main =$("#zipcodemain").val();
	//person
	var salutation_person =$("#salutationperson").val();
	var firstname_person =$("#firstnameperson").val();
	var lastname_person =$("#lastnameperson").val();
	var designation_person =$("#designationperson").val();
	var phone_person =$("#phoneperson").val();
	var extn_person =$("#extnperson").val();
	var officefax_person =$("#officefaxperson").val();
	var email_person =$("#emailperson").val();
	var mobile_person =$("#mobileperson").val();
	var gender_person =$("#genderperson").val();
	var dateperson =$("#dateperson").val();
	var monthperson =$("#monthperson").val();
	var yearperson =$("#yearperson").val();
	var dateofbirth_person = yearperson+"-"+(parseInt(monthperson)+1)+"-"+dateperson;
	var websiteperson =$("#websiteperson").val();
	//billing
	var title_bill =$("#titlebill").val();
	var address_bill =$("#addressbill").val();
	var country2 =$("#country2").val();
	var state2 =$("#state2").val();
	var city_bill =$("#citybill").val();
	var zipcode_bill =$("#zipcodebill").val();
	//billing contact
	var salutationbill_contact =$("#salutationbillcontact").val();
	var firstname_contactperson =$("#firstnamecontactperson").val();
	var lastname_contactperson =$("#lastnamecontactperson").val();
	var designation_contactperson =$("#designationcontactperson").val();
	var officephone_contactperson =$("#officephonecontactperson").val();
	var extn_contactperson =$("#extncontactperson").val();
	var officefax_contactperson =$("#officefaxcontactperson").val();
	var email_contactperson =$("#emailcontactperson").val();
	var mobile_contactperson =$("#mobilecontactperson").val();
	var gender_contactperson =$("#gendercontactperson").val();
	var date_contactperson =$("#datecontactperson").val();
	var month_contactperson =$("#monthcontactperson").val();
	var year_contactperson =$("#yearcontactperson").val();
	var dateofbirth_contactperson= year_contactperson+"-"+(parseInt(month_contactperson)+1)+"-"+date_contactperson;
	var website_contactperson =$("#websitecontactperson").val();
	//credit card
	var ccFName =$("#ccFName").val();
	var ccNo =$("#ccNo").val();
	var ccType =$("#ccType").val();
	var expiryMonth =$("#expiryMonth").val();
	var expiryYear =$("#expiryYear").val();
	var cvc =$("#cvc").val();
	var ccAddress1 =$("#ccAddress1").val();
	var country3 =$("#country3").val();
	var state3 =$("#state3").val();
	var ccCity =$("#ccCity").val();
	var ccZipCode =$("#ccZipCode").val();
	var creditlimit = $("#creditlimit").val();
	var paymentterms = $("#paymentterms").val();
	var commission = $("#commission").val();
	//vilidity
	var objvalidityDate = "";
	var addValidity = $("[name = addValidity]");
	if(addValidity!=null){
		for(var i =0;i<addValidity.length;i++){
			if($(addValidity[i]).parent().attr("style")=='display: none;'){
				objvalidityDate +=  $(addValidity[i]).attr("startdate")+"'"+$(addValidity[i]).attr("enddate")+"'"+$(addValidity[i]).attr("vcid")+"'"+'DELETE'+",";
			}else{
				objvalidityDate +=  $(addValidity[i]).attr("startdate")+"'"+$(addValidity[i]).attr("enddate")+"'"+$(addValidity[i]).attr("vcid")+"'"+'ADD'+",";
			}
		}
		objvalidityDate = objvalidityDate.substring(0, objvalidityDate.length-1);
	}
	//pos commission
	var objaddposcommis = "";
	var addposcommission = $("[name*=poscommissionPers]");
	if(addposcommission!=null){
		for(var i =0;i<addposcommission.length;i++){
			if($(addposcommission[i]).parent().parent().attr("style")=='display: none;'){
				objaddposcommis += $(addposcommission[i]).attr('pospointId')+"'"+$(addposcommission[i]).val()+"'"+$(addposcommission[i]).attr("id")+"'"+'DELETE'+",";
			}else{
				objaddposcommis += $(addposcommission[i]).attr('pospointId')+"'"+$(addposcommission[i]).val()+"'"+$(addposcommission[i]).attr("id")+"'"+'ADD'+",";
			}
		}
		objaddposcommis = objaddposcommis.substring(0, objaddposcommis.length-1);
	}
	//cc
	var ccDelete = $("[id*=Trcc]");
	var delCC = "";
	if(ccDelete!=null){
		for(var i=0;i<ccDelete.length;i++){
			if($(ccDelete[i]).attr("style")=='display: none;'){
				delCC += $(ccDelete[i]).attr("id").substr(4)+',';
			}
		}
		delCC = delCC.substring(0, delCC.length-1);
	}
	
	var url = "/agencyService";
	if(id == null){
		var func = "addcorporate";
	}else{
		var func = "editcorporate"
	}
	var data = { func : func,
			id : id,
			title : title,address_main : address_main,country_main : country_main,state_main : state_main,city_main : city_main,zipcode_main:zipcode_main,
			salutation_person:salutation_person,firstname_person:firstname_person,lastname_person:lastname_person,designation_person:designation_person,phone_person:phone_person,
			extn_person:extn_person,officefax_person:officefax_person,email_person:email_person,mobile_person:mobile_person,gender_person:gender_person,dateofbirth_person:dateofbirth_person,websiteperson:websiteperson,
			title_bill:title_bill,address_bill:address_bill,country2:country2,state2:state2,city_bill:city_bill,zipcode_bill:zipcode_bill,
			salutationbill_contact:salutationbill_contact,firstname_contactperson:firstname_contactperson,lastname_contactperson:lastname_contactperson,
			designation_contactperson:designation_contactperson,officephone_contactperson:officephone_contactperson,extn_contactperson:extn_contactperson,
			officefax_contactperson:officefax_contactperson,email_contactperson:email_contactperson,mobile_contactperson:mobile_contactperson,
			gender_contactperson:gender_contactperson,dateofbirth_contactperson:dateofbirth_contactperson,website_contactperson:website_contactperson,
			ccFName:ccFName,ccNo:ccNo,ccType:ccType,expiryMonth:expiryMonth,expiryYear:expiryYear,cvc:cvc,ccAddress1:ccAddress1,country3:country3,state3:state3,
			ccCity:ccCity,ccZipCode:ccZipCode,creditlimit:creditlimit,paymentterms:paymentterms,commission:commission,objvalidityDate:objvalidityDate,
			objaddposcommis:objaddposcommis,delCC:delCC,type:"agent"
	}
	simpleserviceWithArgs(url,data,showAgent,"add");
}

function gotoeditAgent(id,type){
	waitingDialog({});
	$("[id=tableaddagent]").attr("style","display:;");
	$("[id=tableaddagent]").load("/adminconsole/Console/Agent/AddAgent.jsp",function(responseText, textStatus, XMLHttpRequest) {
			setBarAgent(id,type);
			EditAgentset(id);
			$("#btnAddAgent").attr("onclick","AddEventClickAgent("+id+")");
		$("[id=tableagent]").attr("style","display:none");
	});
}

function EditAgentset(id){
	if(id != null){
		var url = "/agencyService";
		var data = { func : "getCorporateById",
				agencyId : id
			}
		simpleserviceWithArgs(url,data,editSuccessAgent);
	}
}

function editSuccessAgent(data,dialog){
	objArray = JSON.parse(data);
	var checkLogOut = checkSessionAdmin(objArray);
	if(checkLogOut)
		return;
	var textcredit = "";
	var cclist = objArray.listcredit;
	if(cclist!=null){
		for(var i =0;i<cclist.length;i++){
			textcredit += '<tr id="Trcc'+cclist[i].id+'">'+
							'<td align="center" valign="top">'+cclist[i].id+'</td>'+				
							'<td align="center" valign="top">'+cclist[i].NameOnCard+'</td>'+
							'<td align="center" valign="top">'+cclist[i].CardNumber+'</td>'+
							'<td align="center" valign="top">'+cclist[i].CardType+'</td>'+
							'<td align="center" valign="top">'+cclist[i].ExpiryDate+'</td>'+
							'<td align="center" valign="top"><a href="javascript:void(0)" onclick="return deleteCCCard('+cclist[i].id+');">'+text_delete+'</a>'+
							'</td>'+
						'</tr>';
		}
		$("#listagentcredit").replaceWith(textcredit);
	}
	var vclist = objArray.listValidity;
	if(vclist!=null){
		var vclisttext = "";
		for(var i =0;i<vclist.length;i++){
			var startdate = new Date(vclist[i].startdate).getFormatedString();
			var enddate = new Date(vclist[i].enddate).getFormatedString();
			var startDateValue = new Date(vclist[i].startdate).toFormatString("yyyy-MM-dd");
			var endDateValue = new Date(vclist[i].enddate).toFormatString("yyyy-MM-dd");
			vclisttext += "<tr trvalidity="+vclist[i].id+" ><td name='addValidity' startDate = '"+startDateValue+"' endDate = '"+endDateValue+"' vcid = '"+vclist[i].id+"'  >"+console_validity+startdate+" "+console_to+enddate+"</td>" +
			' <td align="left" ><span class="link" startdate='+startDateValue+' enddate='+endDateValue+'  vcid = '+vclist[i].id+' onclick="ValidityAgent($(this))">'+text_charge+'</span>|'+
			'<span class="link" id='+vclist[i].id+' onclick="delValidity(this)" >'+text_delete+'</span>'+
			'</td></tr>';
		}
		$("#listvalidity").replaceWith(vclisttext+"<tr id='listvalidity'></tr>");
	}
	
	var poscomlist = objArray.listposcommis;
	if(poscomlist!=null){
		var poscomtext = '';
		for(var i =0;i<poscomlist.length;i++){
			poscomtext +='<tr trpospointid = '+poscomlist[i].pospointId+'>'+
				'<td></td>'+
				'<td>'+poscomlist[i].titlepospoint+'</td>'+
				'<td>'+
					'<input type="text" name="poscommissionPers[]" style="width:30px;" id='+poscomlist[i].id+' pospointId='+poscomlist[i].pospointId+' consoleId='+poscomlist[i].consoleId+' value='+poscomlist[i].discount+' >%</td>'+
				'<td><span class="link" id='+poscomlist[i].pospointId+' onclick="delPosPoint(this)" >'+text_delete+'</span>'+
				'</td>'+
			'</tr>';
		}
		$("#posRow_checked").replaceWith(poscomtext+"<tr id='posRow_checked'></tr>");
	}
	$("#title").val(objArray.agent);
	//main
	$("#addressmain").val(objArray.mainaddress);
	$("#countrymain").val(objArray.maincountry);
	var t1 = $("[id*=country]:visible")[0].selectedIndex;
	print_stateCorporate("statemain",t1);
	$("#statemain").val(objArray.mainstate);
	$("#citymain").val(objArray.maincity);
	$("#zipcodemain").val(objArray.mainzipcode);
	//person
	$("#salutationperson").val(objArray.salutationperson);
	$("#firstnameperson").val(objArray.firstnameperson);
	$("#lastnameperson").val(objArray.lastnameperson);
	$("#designationperson").val(objArray.designationperson);
	$("#phoneperson").val(objArray.phoneofficeperson);
	$("#extnperson").val(objArray.extendperson);
	$("#officefaxperson").val(objArray.officefaxperson);
	$("#emailperson").val(objArray.emailperson);
	$("#mobileperson").val(objArray.mobileperson);
	$("#genderperson").val(objArray.genderperson);
	var dobperson = new Date(objArray.dobperson);
	$("#dateperson option[value='"+dobperson.getDate()+"']").attr('selected','selected');
	$("#monthperson option[value='"+dobperson.getMonth()+"']").attr('selected','selected');
	$("#yearperson option[value='"+dobperson.getFullYear()+"']").attr('selected','selected');
	$("#websiteperson").val(objArray.websiteperson);
	//billing
	$("#titlebill").val(objArray.billtitle);
	$("#addressbill").val(objArray.billaddress);
	$("#country2").val(objArray.billcountry);
	var t2 = $("[id*=country2]:visible")[0].selectedIndex;
	print_stateCorporate("state2",t2);
	$("#state2").val(objArray.billstate);
	$("#citybill").val(objArray.billcity);
	$("#zipcodebill").val(objArray.billzipcode);
	//billing contact
	$("#salutationbillcontact").val(objArray.contactsalutaion);
	$("#firstnamecontactperson").val(objArray.contactfirstname);
	$("#lastnamecontactperson").val(objArray.contactlastname);
	$("#designationcontactperson").val(objArray.contactdesignation);
	$("#officephonecontactperson").val(objArray.contactofficephone);
	$("#extncontactperson").val(objArray.contactextend);
	$("#officefaxcontactperson").val(objArray.contactofficefax);
	$("#emailcontactperson").val(objArray.contactemail);
	$("#mobilecontactperson").val(objArray.contactmobile);
	$("#gendercontactperson").val(objArray.contactgender);
	var contactdob = new Date(objArray.contactdob)
	$("#datecontactperson").val(contactdob.getDate());
	$("#monthcontactperson").val(contactdob.getMonth());
	$("#yearcontactperson").val(contactdob.getFullYear());
	$("#websitecontactperson").val(objArray.contactwebsite);
	$("#creditlimit").val(objArray.creditlimit);
	$("#paymentterms").val(objArray.paymentterms);
	$("#commission").val(objArray.discount);
	closeWaitingDialog();
}

function changeStatusAgnet(id){
	waitingDialog({});
	var url = "/agencyService";
	var data = { func : "editStatusCorporateById",
			id : id
		}
	simpleservice(url,data,changeStatusSuccessAgent);
}
function changeStatusSuccessAgent(data){
	var objArray = new Array();
	objArray = JSON.parse(data);
	var checkLogOut = checkSessionAdmin(objArray);
	if(checkLogOut)
		return;
	$("#status"+objArray["id"]).text(objArray["status"]);
	if($("#loadingScreen").is(":visible")) closeWaitingDialog();
}

function deleteAgent(){
	waitingDialog({});
	var listCheckBox = "";
	for(var i = 0;i<$('tr [type=checkbox]').not($('tr [type=checkbox]').first()).length;i++){
		if($('tr [type=checkbox]').not($('tr [type=checkbox]').first())[i].checked == true){	
			listCheckBox += $($('tr [type=checkbox]').not($('tr [type=checkbox]').first())[i]).attr("value")+",";
		}
	}
	var url = "/agencyService";
	var data = { func : "delcorporate",
			agencyId : listCheckBox.substring(0,listCheckBox.length - 1)
		}
	simpleserviceWithArgs(url,data,showAgent,"del");
}

function DetailAgent(dom,id){
	waitingDialog({});
	$("[id=tableaddagent]").attr("style","display:;");
	$("[id=tableaddagent]").load("/adminconsole/Console/Agent/DetailAgent.jsp",function(responseText, textStatus, XMLHttpRequest) {
			setTitleBar("detail",profile_agent);
		$("[id=tableagent]").attr("style","display:none");
		DetailAgentset(id);
	});
}

function DetailAgentset(id){
	if(id != null){
		var url = "/agencyService";
		var data = { func : "getCorporateById",
				agencyId : id
		}
		simpleserviceWithArgs(url,data,detailSuccessAgent);
	}
}

function detailSuccessAgent(data){
	var objArray = new Array();
	objArray = JSON.parse(data);
	var checkLogOut = checkSessionAdmin(objArray);
	if(checkLogOut)
		return;
	$("#corpName").html(objArray.agent);
	var personGender = "";
	if(objArray.genderperson!=null){
		if(objArray.genderperson=="fm")
			personGender = console_text_female;
		else
			personGender = console_text_male;
	}
	var contactGender = "";
	if(objArray.contactgender!=null){
		if(objArray.contactgender=="fm")
			contactGender = console_text_female;
		else
			contactGender = console_text_male;
	}
	var dobperson = "";
	if(objArray.dobperson!=null){
		var date = new Date(objArray.dobperson);
		dobperson =	date.getFormatedString();
	}
	var contactdob = "";
	if(objArray.contactdob!=null){
		var date = new Date(objArray.contactdob);
		contactdob =	date.getFormatedString();
	}
	$("#officeAddress").html(objArray.mainaddress+"<br>"+objArray.maincountry+"<br>"+objArray.mainstate+"<br>"+objArray.maincity+"<br>"
			+console_zipcode+" : "+objArray.mainzipcode+"<br><br>"+console_contactperson+" "+objArray.salutationpersonStr+" "+objArray.firstnameperson+
			"  "+objArray.lastnameperson+"<br>"+objArray.designationperson+"<br>"+personGender+" "+dobperson+"<br><br>"+
			console_tel+" "+objArray.mobileperson+"  "+console_ext+" "+
			objArray.extendperson+"<br>"+
			console_fax+objArray.officefaxperson+"<br>"+console_mobile+" : "+objArray.mobileperson+"<br>"+console_email+" : <a href="+objArray.emailperson+">"+objArray.emailperson+"</a><br>"+
			console_website+" : <span class='link'>"+objArray.websiteperson+"</span><br>"
	);
	$("#commissionValue").html(objArray.discount+" %");
	var vclist = objArray.listValidity;
	var vclisttext = "";
	if(vclist!=null){
		for(var i =0;i<vclist.length;i++){
			var startdate = new Date(vclist[i].startdate).getFormatedString();
			var enddate = new Date(vclist[i].enddate).getFormatedString();
			var startDateValue = new Date(vclist[i].startdate).toFormatString("yyyy-MM-dd");
			var endDateValue = new Date(vclist[i].enddate).toFormatString("yyyy-MM-dd");
			vclisttext += "&nbsp;&nbsp;<span>"+startdate+" "+console_to+enddate+"</span><br>";
		}
		$("#commissionListDate").replaceWith(vclisttext);
	}
	var poscomlist = objArray.listposcommis;
	var poscomtext = '';
	if(poscomlist!=null){
		for(var i =0;i<poscomlist.length;i++){
			poscomtext +=poscomlist[i].titlepospoint+poscomlist[i].discount+'% &nbsp;&nbsp;';
		}
		$("#poscommissionList").replaceWith(poscomtext);
	}
	$("#mainBillingAddress").html(
			objArray.billtitle+"<br>"+objArray.billaddress+"<br>"+objArray.billcountry+"<br>"+objArray.billstate+"<br>"+objArray.billcity+"<br>"+
			console_zipcode+" : "+objArray.billzipcode+"<br><br>"
	);
	$("#contactPerson").html(
			console_contactperson+" "+objArray.contactsalutationStr+" "+objArray.contactfirstname+" "+objArray.contactlastname+"<br>"+
			objArray.contactdesignation+"<br>"+contactGender+" "+contactdob+"<br><br>"+
			console_tel+" "+objArray.contactmobile+"  "+console_ext+" "+objArray.contactextend+"<br>"+	
			console_fax+objArray.contactofficefax+"<br>"+console_mobile+" : "+objArray.contactmobile+"<br>"+console_email+
			" : <a href="+objArray.contactemail+">"+objArray.contactemail+"</a><br>"+
			console_website+" : <span class='link'>"+objArray.contactwebsite+"</span><br>"
	);
	//btn
	$("#btnAgent").replaceWith('<div class="ui-newdialog-button bgAdd">'+
		    '<div style="text-align:center;">'+
	        '<button id="btnAgent" style="text-align:center" class="btn" onclick="gotoeditAgent('+objArray.id+','+"'detailedit'"+')">'+console_btn_edit+'</button>'+
	        '<button onclick="showAgent()" style="text-align:center" class="btn">'+console_btn_cancel+'</button>'+
	    '</div>'+
	    '</div>'
	);
	//code
	$("#codecoporate").html(objArray.displayId);
	closeWaitingDialog();
}

function discCorp(){
	if($("#trdisccorp").css("display")=="none"){
		$("#trdisccorp").attr("style","display:");
	}else{
		$("#trdisccorp").attr("style","display:none");
	}
}
//pos commission
function posAgent(dom){
	var dialog = editAdminDataDialog("left,top",dom,label_addposcommission,"/adminconsole/Console/Agent/AddPOSCorporate.jsp","addDialog",AddEventValidityAgent,loadValidityPOSElementFinish,null);
}
function loadValidityPOSElementFinish(daialog){
	$("[id*=BlankDialog]:visible").attr("tabindex",-1).focus();
	$("[id*=BlankDialog]:visible").css('outline', 'none');
	getPosPoint();
}
function getPosPoint(){
	var link = "/POSService";
	var data = { func: "getAllPOS"}
	simpleservice(link,data,getPosPointSuccess);
}
function getPosPointSuccess(data){
	objArray = JSON.parse(data);
	var checkLogOut = checkSessionAdmin(objArray);
	if(checkLogOut)
		return;
	var textPosPoint = "";
	var poscommission= $("[name*=poscommissionPers]");
	var checkpospoint = true;
	for(var i=0;i<objArray.length;i++){
		for(var p =0;p<poscommission.length;p++){
			if(parseInt($(poscommission[p]).attr('pospointid'))==objArray[i].id){
				checkpospoint = false;
				break;
			}else{
				checkpospoint = true;
			}
		}
		if(checkpospoint){
			textPosPoint += '<tr style="border: 0px;">'+
			'<td id="col_1" align="center">1</td>'+
			'<td><input type="checkbox" id='+objArray[i].id+' name="ids[]" title='+objArray[i].Title+'></td>'+
			'<td class="main-field">'+objArray[i].Title+'</td>'+
			'<td align="center">'+
				'<input class="input-style3" type="text" numberonly="true" name="value'+objArray[i].id+'" value="0" size="2" maxlength="5">%'+
			'</td>'+
			'</tr>';
		}
	}
	$("[id*=tr_poscommission]:visible").replaceWith(textPosPoint);
	var listPOS = $("[numberonly]");
	for(var i =0;i<listPOS.length;i++){
		ForceNumericOnly($(listPOS[i]));
	}
}
function delPosPoint(element){
	$("[trpospointid="+$(element).attr('id')+"]").css("display","none");
}
//validity
function AddEventValidityAgent(dialog){
	$("[edit=true]").removeAttr("edit");
	var checkpos = dialog.find("[name*=ids]");
	var textPosChecked = "";
	for(var i=0;i<checkpos.length;i++){
		var checkedPos = $(checkpos[i]).is(":checked");
		if(checkedPos){
			var value = dialog.find("[name=value"+checkpos[i].id+"]").val();
			textPosChecked += '<tr trpospointid='+checkpos[i].id+'><td></td>'+
			'<td>'+checkpos[i].title+'</td>'+
			'<td><input type="text" pospointId='+checkpos[i].id+' name="poscommissionPers[]" style="width:30px;"  value='+value+'>%</td>'+
			'<td><span class="link" id='+checkpos[i].id+' onclick="delPosPoint(this)" >'+text_delete+'</span>'+
			'</td></tr>';
		}
	}
	$("#posRow_checked").replaceWith(textPosChecked+"<tr id='posRow_checked'></tr>");
}
function ValidityAgent(doms,type){
	if(type=="EDIT"){
		$("[edit=true]").removeAttr("edit");
		doms.parent().parent().attr("edit","true");
	}
	$("#addvaliditycorp").dialog({
		width : 525,
		resizable : false,
		modal : true,
		zIndex: 200001,
		show : {
			effect : "blind",
			duration : 500
		},
		open: function(event, ui) {
			$(this).css('overflow', 'hidden');
			$("#addvaliditycorp").dialog('option','title',console_addvalidity);
			var dateStart = doms.attr('startdate');
			var dateEnd =doms.attr("enddate");
			var vcId = doms.attr("vcid");
			setDatepicker(dateStart,dateEnd,vcId);
	    }
	});
}
function addValidityCorp(dialog){
	var startDate 	= $("[name=srTxtFrom]").attr("valfrom");
	var endDate 	= $("[name=srTxtTo]").attr("valfrom");
	var startDatetoString = new Date(startDate).getFormatedString();
	var endDatetoString = new Date(endDate).getFormatedString();
	var checkupdate = $("[name=srTxtFrom]").attr("startdate");
	if(checkupdate!=null&&checkupdate!=""){
		var element = $("[name=addValidity]");
		for(var i =0;i<element.length;i++){
			var idChange = $("[name='srTxtFrom']:visible").attr("vcid");
			var idCheck = $(element[i]).attr("vcid");
			if(idChange==idCheck){
				$(element[i]).replaceWith("<td name='addValidity' startDate = '"+startDate+"' endDate = '"+endDate+"' vcid='"+idChange+"'>"+console_validity+startDatetoString+console_to+endDatetoString+"</td>");
			}
		}
	}else{
		var text = "<tr ><td name='addValidity' startDate = '"+startDate+"' endDate = '"+endDate+"'>"+console_validity+startDatetoString+console_to+endDatetoString+"</td>" +
		' <td align="left">'+
		'<span class="link" startdate='+startDate+' enddate='+endDate+'  onclick="ValidityAgent($(this),'+"'EDIT'"+')">'+text_charge+'</span>|'+
		'<span class="link"  onclick="delValidity(this)" >'+text_delete+'</span></td>'+
		'</tr>';
		if($("[edit=true]").size()!=0){
			$("[edit=true]").replaceWith(text);
		}else{
			$("#listvalidity").replaceWith(text+"<tr id='listvalidity'></tr>");
		}
	}
	$('#addvaliditycorp').dialog('close');
}

function delValidity(element){
	if($(element).attr('id')!=null)
		$("[trvalidity="+$(element).attr('id')+"]").css("display","none");
	else
		$(element).parent().parent().remove();
}
// deleteccCard
function deleteCCCard(id){
	$("#Trcc"+id).css("display","none");
}